desde(X, X).
desde(X, Y) :- ( var(Y) -> N is X+1, desde(N, Y); X<Y).


esTriangulo(tri(A,B,C)) :- esComp(A,B,C), esComp(B,A,C), esComp(C,A,B).

esComp(A,B,C) :- A<B+C, 0<A.




perimetro(T,P) :- (var(T) -> desde(3,P), generarTriangulosDePerimetro(T,P); sumar(T,P)).

sumar(tri(A,B,C), N) :- N is A+B+C, esTriangulo(tri(A,B,C)).


generarTriangulosDePerimetro(tri(An,Bn,Cn),P) :- entre(1, P, An), entre(1, P-An, Bn), entre(1, P-An-Bn, Cn), sumar(tri(An,Bn,Cn),P).



entre(X,Y,X) :- X =< Y.
entre(X,Y,Z) :- X < Y, N is X+1, entre(N,Y,Z).

min(X,Y,Z) :- X<Y, Z is X.
min(X,Y,Z) :- Y=<X, Z is Y.

%obtenerMinimo(L, M) :- sumList(L, SL), append(L1, L2, L), minDiff(L1, L2, SL, M).

%minDiff(L1, L2, Actual, N) :- sumlist(L1, S1), sumlist(L2, S2), 
%		abs(S1-S2, Df), min(Actual, Df, N).


cortarParejo(L, L1, L2) :- minDiff(L,Q), append(L1, L2, L), sumlist(L1, S1), sumlist(L2, S2), 
		abs(S1-S2, Q). 

minDiff([X|L],Z):- sumlist([X], S1), sumlist(L, S2), abs(S1-S2, Df), minDiffAux([X],L,Df,Z).

minDiffAux(L,[],Df,Z):- sumlist(L, S1), min(S1,Df,Z).
minDiffAux(L,[X|R],Df1,Z):- append(L,[X],Lx), sumlist(Lx, S1), sumlist(R,S2), abs(S1-S2,Df2), min(Df1,Df2,Q), minDiffAux(Lx,R,Q,Z).


cortar2(L, L1, L2) :- append(L1, L2, L), difff(L1, L2, N), not((append(P1, P2, L), difff(P1, P2, M), M<N)).

difff(L1, L2, S) :- sumlist(L1, S1), sumlist(L2, S2), abs(S1-S2, S). 
